import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class SqlitePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SqlitePage();
  }
}

class _SqlitePage extends State<SqlitePage> {
  final _userNameController = new TextEditingController();
  final _userPwdController = new TextEditingController();

  //获取路径
  Future<String> get _dbPath async {
    var directory = await getApplicationDocumentsDirectory();
    String path = directory.path + "user.db";
    return path;
  }

  //创建数据库
  Future<Database> get _localFile async {
    final path = await _dbPath;
    var db = openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      await db.execute(
          "CREATE TABLE user (id INTEGER PRIMARY KEY, name TEXT,pwd TEXT)");
    });
    return db;
  }

  //保存数据
  Future<int> save(String name, String pwd) async {
    final db = await _localFile;
    return db.transaction((trx) {
      trx.rawInsert('INSERT INTO user(name,pwd) VALUES("$name","$pwd")');
    });
  }

  //获取数据
  Future<List<Map>> get() async {
    final db = await _localFile;
    List<Map> list = await db.rawQuery('SELECT * FROM user');
    return list;
  }

  @override
  void initState() {
    super.initState();
    get().then((list) {
      var data = list[0] ?? null;
      if (data != null) {
        print(data);
        _userNameController.text = data["name"];
        _userPwdController.text = data["pwd"];
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        //leading: Icon(Icons.arrow_back),
        title: Text("Sqlite"),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          TextField(
            controller: _userNameController,
            maxLines: 1,
            decoration: InputDecoration(
              contentPadding: const EdgeInsets.only(top: 10.0),
              icon: Icon(Icons.person),
              labelText: "请输入用户名",
              helperText: "注册时填写的名字",
            ),
          ),
          TextField(
            controller: _userPwdController,
            maxLines: 1,
            decoration: InputDecoration(
              contentPadding: const EdgeInsets.only(top: 10.0),
              icon: Icon(Icons.keyboard),
              labelText: "请输入密码",
              helperText: "注册时填写的密码",
            ),
          ),
          Builder(builder: (ctx) {
            return RaisedButton(
                child: Text("登录"),
                onPressed: () {
                  if (_userNameController.text.toString().isEmpty) {
                    Scaffold.of(ctx).showSnackBar(SnackBar(
                      content: Text("请输入用户名"),
                      duration: Duration(seconds: 1),
                    ));
                    return;
                  }
                  if (_userPwdController.text.toString().isEmpty) {
                    Scaffold.of(ctx).showSnackBar(SnackBar(
                      content: Text("请输入密码"),
                      duration: Duration(seconds: 1),
                    ));
                    return;
                  }
                  if (_userPwdController.text.toString() == "123456") {
                    Scaffold.of(ctx).showSnackBar(SnackBar(
                      content: Text("登录成功"),
                      duration: Duration(seconds: 1),
                    ));
                    save(_userNameController.text.toString(),
                        _userPwdController.text.toString());
                  } else {
                    Scaffold.of(ctx).showSnackBar(SnackBar(
                      content: Text("登录失败"),
                      duration: Duration(seconds: 1),
                    ));
                  }
                });
          })
        ],
      ),
    );
  }
}
